package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.oss.service.FileService;
import com.atguigu.yygh.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    //文件上传
    @Override
    public String uploadFile(MultipartFile file) {

        //1,初始化获取参数 创建客户端对象
        //1.1 获取参数
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        try {

            //1.2创建客户端对象
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //准备参数
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            //保证上传的文件名不重复
            String uuid=UUID.randomUUID().toString().replaceAll("-","");
            filename=uuid+filename;
            //按照当前日期创建文件夹，上传文件到文件夹里
            String timeUrl=new DateTime().toString("yyyy/MM/dd");
            filename=timeUrl+"/"+filename;

            //客户端对象调用方法 上传文件
            ossClient.putObject(bucketName,filename,inputStream);
            ossClient.shutdown();

            //返回url
            //https://xiaoaxing.oss-cn-beijing.aliyuncs.com/6b53b7dc9bb94b2a9377060458c6d2e4.jpg
                String url="https://"+bucketName+"."+endpoint+"/"+filename;
            return url;

        } catch (IOException e) {
            e.printStackTrace();

            throw new YyghException(20001,"文件上传失败");
        }

    }
}
